;; https://projecteuler.net/problem=4

;; Largest palindrome product

;; Problem 4

;; A palindromic number reads the same both ways. The
;; largest palindrome made from the product of two 2-digit
;; numbers is 9009 = 91 × 99.

;; Find the largest palindrome made from the product of two
;; 3-digit numbers.


(import
  (except (rnrs base) let-values)
  (only (guile)
        ;; lambda forms
        lambda* λ
        sqrt)
  (srfi srfi-1))


(define palindrome-number?
  (λ (num)
    (let ([num-as-str (number->string num)])
      (string=? (reverse-list->string (string->list num-as-str))
                num-as-str))))


(define find-palindrome-products
  (λ ()
    (let next ([fac-outer 100] [fac-inner 100] [found-max-palimdrome '0])
      (cond
       [(> fac-outer 999)
        found-max-palimdrome]
       [(> fac-inner 999)
        (next (+ fac-outer 1) 100 found-max-palimdrome)]
       [else
        (let ([product (* fac-outer fac-inner)])
          (cond
           [(palindrome-number? product)
            (simple-format (current-output-port)
                           "~a x ~a = ~a\n"
                           fac-outer
                           fac-inner
                           product)
            (next fac-outer
                  (+ fac-inner 1)
                  (max found-max-palimdrome product))]
           [else
            (next fac-outer
                  (+ fac-inner 1)
                  found-max-palimdrome)]))]))))


(simple-format
 (current-output-port)
 "~a\n"
 (find-palindrome-products))
